library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.2     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.1.0     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(p8105.datasets)

library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout

Clean data/ select items for charts

data("instacart")

icart = instacart |> 
  select(order_id, order_hour_of_day, order_dow, add_to_cart_order, aisle, department)

Top 10 Departments

Bar graph

department_counts = icart |> 
  count(department, name = "items" , sort = TRUE) |>
  slice_head(n = 10)


plot_ly(department_counts,
        x = ~ items, 
        y = ~ reorder(department, items),
        type = "bar"
) |>
layout(
  xaxis = list(title = "Items"),
  yaxis = list(title = "Department")
)

Items per Hour

Line graph:

items_by_hour = icart |> 
  count(order_hour_of_day, name = "items")


plot_ly(items_by_hour,
        x = ~ order_hour_of_day, 
        y = ~ items,
        type = "scatter",
        mode = "lines+markers"
) |>
layout(
  xaxis = list(title = "Order Hour (0–23)"),
  yaxis = list(title = "Items")
)

Typical Order Hour by Day

Box plot

dow_labs = c("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
box_df = icart |>
transmute(
order_dow = factor(order_dow, levels = 0:6, labels = dow_labs),
order_hour_of_day
) |>
drop_na(order_hour_of_day)
plot_ly(box_df,
        x = ~ order_dow, 
        y = ~ order_hour_of_day,
        type = "box"
) |>
layout(
  xaxis = list(title = "Day of Week"),
  yaxis = list(title = "Order Hour (0–23)")
)